package rbac.util;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例⼯⼚类
 * 封装获取某个类的单例实例
 */

public class SingletonFactory {

    // 用于存储 Class对象 与 类单例 之间的映射，采用线程安全的ConcurrentHashMap
    private static final Map<Class<?>, Object> instanceMap =
            new ConcurrentHashMap<>();

        public static <T> T getInstance(Class<T> clazz){
        if (clazz == null){
            throw new IllegalArgumentException("未知的类型");
        }
        if (!instanceMap.containsKey(clazz)){
            try {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                T singleton = constructor.newInstance();
                instanceMap.put(clazz, singleton);
            }catch (Exception e){
                throw new IllegalArgumentException("创建单例模式失败:" + clazz.getSimpleName(), e);
            }
        }
        return (T)instanceMap.get(clazz);
    }


}

